package com.smiier.skin;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.o.app.event.listener.OBitmapLoadCallBack;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OImageView;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.task.RequestTask;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.extra.TreatmentProjectItemExtra;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.QuestionGetTask;
import com.smiier.skin.net.QuestionGetTask.QuestionGetRequest;
import com.smiier.skin.net.QuestionGetTask.QuestionGetResponse;
import com.smiier.skin.net.entity.QuestionAnswer;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.umeng.analytics.MobclickAgent;

/**
 * @{# CreateQuestionSuccessfullyActivity_V1_1.java Create on 2014-10-12
 *     下午1:35:57
 * 
 * @author <a href="mailto:evan0502@qq.com">Evan</a>
 * @version 1.0 创建问题成功界面
 */

@SuppressLint({ "InflateParams", "HandlerLeak" })
public class CreateQuestionSuccessfullyActivity extends BasicActivity {

	// 请求默认推荐医生参数
	HashMap<String, Object> params = new HashMap<String, Object>();

	private LinearLayout ll_cost;

	private LinearLayout ll_recommend_doctor;

	private TextView mTextHour;

	private TextView mTextMin;

	private TextView mTextSec;

	// 倒计时运行标记
	boolean isRunning = true;
	boolean isTreatmentReserve = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_question_successfully);
		Intent i = getIntent();
		isTreatmentReserve = i.getBooleanExtra(Constant.IDENTITY_KEY, false);
		ll_cost = (LinearLayout) findViewById(R.id.ll_cost);
		ll_recommend_doctor = (LinearLayout) findViewById(R.id.ll_recommend_doctor);
		mTextHour = (TextView) findViewById(R.id.text_hour);
		mTextMin = (TextView) findViewById(R.id.text_min);
		mTextSec = (TextView) findViewById(R.id.text_sec);

		init();
		if (isTreatmentReserve) {
			setNavTitle("创建预约成功");
			TextView create = (TextView) findViewById(R.id.create);
			TextView tip = (TextView) findViewById(R.id.tip);
			Button button = (Button) findViewById(R.id.btn_cost);
			create.setText("创建预约成功");
			tip.setText("我们会尽快与医院沟通确认您的预约，请耐心等待，预约成功后您会收到确认短信");
			button.setText("查看我的项目");
			setNavLeftBtnGone();
		} else {
			setNavTitle("创建成功");
		}

		// setNavRightBtn("查看问题");
		setNavRightBtn("确认");
		boolean isCost2Doctor = getIntent().getBooleanExtra(
				Constant.IDENTITY_KEY_CREATE_COST_2_DOCTOR, false);
		if (isCost2Doctor) {
			ll_cost.setVisibility(View.GONE);
		}

		params.put(Constant.PARAM_API, "User.GetList");
		params.put("pageSize", 3);
		params.put("User_Type", 2);
		params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
		params.put("Default", 1);

		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						if (!CommonUtility.isNull(o)) {
							try {
								JSONObject object = (JSONObject) o;
								if (CommonUtility.response200(object)) {
									object = object.getJSONObject("Res");
									JSONArray array = object
											.getJSONArray("Users");
									for (int i = 0; i < array.length(); i++) {
										object = (JSONObject) array
												.getJSONObject(i);
										JSONObject doctor = object
												.getJSONObject("User");
										View view = LayoutInflater.from(
												activity).inflate(
												R.layout.item_doctor, null);
										OImageView img = (OImageView) view
												.findViewById(R.id.imgLayout_show);
										TextView text_doctor_name = (TextView) view
												.findViewById(R.id.text_doctor_name);
										TextView text_doctor_skill = (TextView) view
												.findViewById(R.id.text_doctor_skill);
										TextView text_doctor_hospital = (TextView) view
												.findViewById(R.id.text_doctor_hospital);
										TextView text_doctor_title = (TextView) view
												.findViewById(R.id.text_doctor_title);
										TextView text_charge = (TextView) view
												.findViewById(R.id.text_charge);

										mBitmapUtils
												.display(
														img,
														GlobalSettings.SERVER_IMG_URL
																+ doctor.getString("Pic")
																+ Constant.IMG_SRC,
														new OBitmapLoadCallBack<View>());
										text_doctor_name.setText(doctor
												.getString("Name"));
										text_doctor_skill
												.setVisibility(View.VISIBLE);
										text_doctor_skill.setText(CommonUtility.convertJSONArray2String(
												doctor.getJSONArray("Skilled"),
												" | "));
										JSONArray professional = doctor
												.getJSONArray("Professional");
										text_doctor_title.setText(CommonUtility
												.convertJSONArray2String(
														professional, ","));
										text_doctor_hospital.setText(doctor
												.getString("Hospital"));
										StringBuilder sb = new StringBuilder();
										double cost = doctor.getDouble("Cost");
										String charge = "图文咨询";
										if (cost > 0) {
											charge = cost + "";
											if (charge.endsWith(".0")) {
												charge = charge.substring(0,
														charge.length() - 2);
											}
											sb.append("￥").append(charge)
													.append(" / 问题");
										} else {
											sb.append(charge);
										}
										text_charge.setText(sb);
										view.setOnClickListener(doctorListener);
										view.setTag(doctor);
										ll_recommend_doctor.addView(view);
									}
								} else {
									CommonUtility.toast(activity,
											R.string.server_unavailable);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}), params);

		// 倒计时线程
		new Thread() {

			@Override
			public void run() {
				try {
					while (isRunning) {
						Thread.sleep(1000);
						handler.sendEmptyMessage(0);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			int hour = Integer.parseInt(CommonUtility.getText(mTextHour));
			int min = Integer.parseInt(CommonUtility.getText(mTextMin));
			int sec = Integer.parseInt(CommonUtility.getText(mTextSec));

			sec--;
			if (sec < 0) {
				min--;
				sec = 59;
				if (min < 0) {
					hour--;
					min = 59;
				}
			}

			mTextHour.setText(new StringBuilder("0").append(hour));
			if (min < 10) {
				mTextMin.setText(new StringBuilder("0").append(min));
			} else {
				mTextMin.setText(min + "");
			}
			if (sec < 10) {
				mTextSec.setText(new StringBuilder("0").append(sec));
			} else {
				mTextSec.setText(sec + "");
			}
		}
	};

	OnClickListener doctorListener = new OnClickListener() {

		@SuppressWarnings("unchecked")
		@Override
		public void onClick(View view) {
			final JSONObject doctorInfo = (JSONObject) view.getTag();
			Intent intent = null;
			try {
				double cost = doctorInfo.getDouble("Cost");
				if (cost > 0) {
					intent = new Intent(activity, Cost2DoctorActivity.class);
					intent.putExtra(Constant.IDENTITY_KEY_COST_MUST_OVER_ZERO,
							true);
					intent.putExtra(Constant.IDENTITY_KEY,
							doctorInfo.toString());
					intent.putExtra(Constant.IDENTITY_KEY_QUESTION_ID,
							getIntent().getStringExtra(Constant.IDENTITY_KEY));
					startActivity(intent);
				} else {
					HashMap<String, Object> params = new HashMap<String, Object>();
					params.put(Constant.PARAM_API, "Question.Set");
					params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
					params.put("Is_Appoint", 1);
					params.put("Doctor_Uid", doctorInfo.getString("Uid"));
					params.put("qid",
							getIntent().getStringExtra(Constant.IDENTITY_KEY));
					params.put("Status", 2);
					new RequestTask(activity, Constant.URL.REQUEST,
							new RequestHandler(activity, new HandlerCallback() {

								@Override
								public void callback(Object o) {
									if (!CommonUtility.isNull(o)) {
										JSONObject object = (JSONObject) o;
										if (CommonUtility.response200(object)) {
											try {
												Intent intent = new Intent(
														activity,
														CreateQuestionSuccessAndChatActivity.class);
												object = object
														.getJSONObject(Constant.JSON_PARAM_RES);
												intent.putExtra(
														Constant.IDENTITY_KEY_DOCTOR_INFO,
														doctorInfo.toString());
												intent.putExtra(
														Constant.IDENTITY_KEY,
														object.getString("Qid"));
												startActivity(intent);
												CommonUtility
														.finishActivityFromName(Cost2DoctorActivity.class
																.getSimpleName());
												CommonUtility
														.finishActivityFromName(Cost2DoctorSuccessActivity.class
																.getSimpleName());
												intent = new Intent(
														Constant.RECIVER_CHAT_LIST);
												sendBroadcast(intent);
												intent = new Intent(
														Constant.RECIVER_UPDATE_QUESTION);
												sendBroadcast(intent);
												intent = new Intent(
														Constant.RECIVER_QUESTION);
												intent.putExtra(
														Constant.IDENTITY_KEY_1,
														true);
												sendBroadcast(intent);
												finish();
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									}
								}
							})).execute(params);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			// Intent intent = new Intent(activity, DoctorDetailActivity.class);
			// intent.putExtra(Constant.IDENTITY_KEY, object.toString());
			// startActivity(intent);
		}
	};

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btn_cost) {
			if (isTreatmentReserve) {
				CommonUtility
						.finishActivityFromName(MyQuestionDetailActivity.class
								.getSimpleName());
				TreatmentProjectItemExtra extra = new TreatmentProjectItemExtra();
				extra.getFrom(getIntent());
				Intent i = new Intent(getContext(),
						TreatmentDetailActivity.class);
				if (extra.putTo(i)) {
					startActivity(i);
				}

			} else {
				QuestionGetTask task = new QuestionGetTask();
				QuestionGetRequest req = new QuestionGetRequest();
				req.qids = new ArrayList<Long>();
				req.token = GlobalSettings.sToken;
				String str = getIntent().getStringExtra(Constant.IDENTITY_KEY);
				JSONObject obj;
				try {
					obj = new JSONObject(str);
					req.qids.add(obj.getLong("Qid"));
					task.setRequest(req);
					task.addListener(new NetTaskListener<QuestionGetTask.QuestionGetRequest, QuestionGetTask.QuestionGetResponse>() {

						@Override
						public void onException(
								INetTask<QuestionGetRequest, QuestionGetResponse> task,
								Exception e) {

						}

						@Override
						public void onComplete(
								INetTask<QuestionGetRequest, QuestionGetResponse> task,
								QuestionGetResponse response) {
							if (response != null && response.Res.size() > 0) {
								QuestionAnswer a = response.Res.get(0);
								Intent i = new Intent(
										CreateQuestionSuccessfullyActivity.this,
										QuestionDetailActivity.class);
								try {
									i.putExtra(Constant.IDENTITY_KEY,
											JsonUtil.convert(a));
									startActivity(// getIntent().setClass(activity,QuestionDetailActivity.class)
									i);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}
						}
					});
					add(task);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				/*
				 * Intent intent = new Intent(activity,
				 * QuestionDetailActivity.class);
				 * intent.putExtra(Constant.IDENTITY_KEY, all.toString());
				 * activity.startActivity(intent);
				 */
			}
		} else if (id == R.id.text_right) {
			if (isTreatmentReserve) {

				Intent i = new Intent(getContext(),
						MyTreatmentProjectListActivity.class);
				startActivity(i);

			} else {
				CommonUtility
						.finishActivityFromName(MyQuestionDetailActivity.class
								.getSimpleName());
				startActivity(new Intent(activity,
						MyQuestionDetailActivity.class));
			}
			finish();
		} else if (id == R.id.btn_left) {
			finish();
		} else if (id == R.id.ll_recommend_doctor) {
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isRunning = false;
	}
	
	
/*	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(getContext());
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/
}
